﻿//======================================================================
//
//        Copyright (C) 2015   
//        All rights reserved
//
//        filename : PutOutCard
//        description : 半成品/成品卡出库
//        created by XXX at  20150821
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using System.Data;
using System.Text;
using CardLogistics.Web.Base;

namespace CardLogistics.Web.MainPage.PutOutCard.PutOutCard
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.PutOutCard.PutOutCardData DAL = new DAL.PutOutCard.PutOutCardData();
        private static readonly CardLogistics.DAL.PutOutCard.PutOutCard_DetailData DDAL = new CardLogistics.DAL.PutOutCard.PutOutCard_DetailData();
        /// <summary>
        /// 盒号集合
        /// </summary>
        protected Dictionary<string, string> CardNOList = null;
        public static string TitleName;
        private static DataTable DtBoxSup;//存放供应商、盒号等信息
        /// <summary>
        /// 箱号号集合
        /// </summary>
        protected string BoxNOList = "";

        protected Dictionary<string, string> CardNOList_D = null;
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            CardNOList = new Dictionary<string, string>();
            CardNOList_D = new Dictionary<string, string>();
            BoxNOList = "";
            if (!IsPostBack)
            {
                PUTOUTCARDDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//出库日期
                TitleName = GetStatusInfo(-1, "半成品/成品卡出库");
                InitControl(sender,e);
            }
        }


        #region 得到一个对象实体
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public void InitControl(object sender, EventArgs e)
        {
            TitleName = GetStatusInfo(0, "半成品/成品卡出库");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    CardLogistics.Model.PutOutCard.PutOutCard pData = DAL.GetModel(_key);
                    SetWebControls(this.Page, pData);
                    hf_ApplyId.Value = pData.APPLYID; //卡片出库申领单Id
                    DataTable dt = DDAL.GetInfoByPutOutCardId(pData.ID);
                    //dt.DefaultView.Sort = "StartNo ASC,EndNo ASC";
                    DataView dv = dt.DefaultView;
                    dv.Sort = "StartNo ASC,EndNo ASC";
                    dt = dv.ToTable();
                    string detId = "";
                    int editCardNum = 0;
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            detId += dr["cardno"].ToString() + "|" + dr["FlagName"].ToString() + "|" + dr["Fgvamt"].ToString() + "|" + dr["PreCharge"].ToString() + "|" + dr["StartCardNo"].ToString() + "|" + dr["EndCardNo"].ToString() + "|" +
                                     dr["duenumber"].ToString() + "|" + dr["actualnumber"].ToString() + "|" + dr["missingcardno"].ToString() + ";";
                            //获取编辑前的卡片数量
                            editCardNum += (Convert.ToInt32(dr["EndCardNo"].ToString()) - Convert.ToInt32(dr["StartCardNo"].ToString()) + 1);
                        }
                        hf_detailId.Value = detId.TrimEnd(';');
                        hf_EditSumCard.Value = editCardNum.ToString(); //获取编辑前的卡片数量
                    }
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (pData.ISSUBMIT == 0 || pData.ISSUBMIT == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    //通过申领ID得到申领总数量和已出库的总数量
                    DataTable putoutdt = CardLogistics.DAL.CommonData.GetList("*", "v_putoutapply", "ID='" + pData.APPLYID + "'");
                    hf_ApplyTotal.Value = putoutdt.Rows[0]["ApplyedTotal"].ToString(); //订单总数量
                    hf_PutOutedTotal.Value = putoutdt.Rows[0]["PutOutedTotal"].ToString();//已入库数量
                    ddlSUPPID.SelectedValue = pData.SUPPID;
                    btn_ApplyId_ValueChanged(sender, e);
                    ddlSUPPID.SelectedValue = pData.SUPPID;
                    ddlSUPPID_selectChange(sender, e);


                    TitleName = GetStatusInfo(int.Parse(pData.ISSUBMIT.ToString()), "半成品/成品卡出库");
                }
            }
            else
            {
                hf_EditSumCard.Value = "0";
                PUTOUTCARDNO.Value = GetBillNumber("半成品/成品卡出库");
            }

        }
        #endregion

        #region 保存事件
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 保存并提交
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }

        }
        #endregion

        #region 提示信息
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(8, result.Split(',')[1]); // 8半成品/成品卡出库
                    InsertLog("保存并提交半成品/成品卡出库信息,出库单号:" + PUTOUTCARDNO.Value);
                }
                else
                    InsertLog("保存半成品/成品卡出库信息,出库单号:" + PUTOUTCARDNO.Value);
                ReturnListInfo();
            }

            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        #region 半成品/成品卡出库信息
        /// <summary>
        /// 半成品/成品卡出库信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            string result = string.Empty;
            CardLogistics.Model.PutOutCard.PutOutCard model = new CardLogistics.Model.PutOutCard.PutOutCard();
            model = GetWebControls<CardLogistics.Model.PutOutCard.PutOutCard>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;
            model.LASTUPDATEDATE = DateTime.Now;
            model.SUPPID = ddlSUPPID.SelectedValue;//供应商
            model.ADDTIME = DateTime.Now;
            model.ISDELETE = 0; //未删除
            model.ISSUBMIT = issubmit;//0 未提交 1 待审核 2 审核中 3 驳回 4 审核不通过 5审核通过
            model.APPLYID = hf_ApplyId.Value; //卡片出库申领单Id
            string FileValue = hf_detailId.Value;
            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model, FileValue);
            }
            else
            {
                result = DAL.Add(model, FileValue);
                if (result.Split(',')[0] == "ok")
                {
                    ChgBillNumber("半成品/成品卡出库");
                }
            }
            return result;
        }
        #endregion

        
        #region 绑定供应商 、盒号
        //根据申领单来绑定供应商
        protected void btn_ApplyId_ValueChanged(object sender, EventArgs e)
        {
            string id = "";
            if (hf_ApplyId.Value != "")
            {
                if (IsEdit)
                    id = Request.QueryString["id"].ToString();
                if (!BaseClass.hs.ContainsKey(hf_ApplyId.Value))
                {
                    DtBoxSup = DAL.GetBoxSupInfo(id, hf_ApplyId.Value);//获取供应商、盒号、卡类型等
                    BaseClass.hs.Add(hf_ApplyId.Value, DtBoxSup);
                }
                //if (DtBoxSup.Rows.Count == 0)
                //    //当审核不通过(IsSubmit=4)时获取白卡出库供应商和盒号等信息
                //    DtBoxSup = CardLogistics.DAL.CommonData.GetList("*", "v_putoutcard_detail", "PutOutCardId='" + id + "' and IsSubmit=4");
                BindSup();
            }
        }

        //根据申领单号查询入库盒号
        private void BindSup()
        {
            ddlSUPPID.Items.Clear();
            ListItem lt = new ListItem("---请选择---", "0");
            ddlSUPPID.Items.Add(lt);

            DtBoxSup = BaseClass.hs[hf_ApplyId.Value] as DataTable;

            if (DtBoxSup != null && DtBoxSup.Rows.Count > 0)
            {
                foreach (DataRow dr in DtBoxSup.Rows)
                {
                    ListItem tmpLt = new ListItem(dr["suppliersname"].ToString(), dr["suppid"].ToString());
                    if (!ddlSUPPID.Items.Contains(tmpLt))
                        ddlSUPPID.Items.Add(tmpLt);
                }
            }
            ddlSUPPID.SelectedValue = "0";
        }
        //根据供应商过滤盒号
        protected void ddlSUPPID_selectChange(object sender, EventArgs e)
        {
            if (ddlSUPPID.SelectedValue != "0")
            {
                string suppid = ddlSUPPID.SelectedValue;
                CardNOList = new Dictionary<string, string>();
                CardNOList_D = new Dictionary<string, string>();
                BoxNOList = "";
                //DtBoxSup.DefaultView.Sort = "CardNo ASC";//按盒号排序
                DataView dv = DtBoxSup.DefaultView;
                dv.Sort = "CardNo ASC";//按盒号排序
                DtBoxSup = dv.ToTable();
                rkId.Value = DtBoxSup.Rows[0]["CheckId"].ToString();//获取入库Id
                zkId.Value = DtBoxSup.Rows[0]["zkId"].ToString();//获取制卡入库Id
                DataRow[] dr = DtBoxSup.Select(" suppid='" + suppid + "'");
                foreach (DataRow d in dr)
                {
                    if (!CardNOList.Keys.Contains(d["cardno"].ToString().Trim()))
                    {
                        //是否启用|卡押金|预充值|开始卡号|结束卡号
                        CardNOList.Add(d["FlagName"].ToString() + "|" + d["Fgvamt"].ToString() + "|" + d["InitAmt"].ToString() + "|" + d["startno"].ToString() + "|" + d["endno"].ToString() + "|" + d["CheckId"].ToString() + "|" + d["zkId"].ToString(), d["cardno"].ToString().Trim());
                    }
                    if (!BoxNOList.Split(',').Contains(d["boxno"].ToString()))
                    {
                        BoxNOList += d["boxno"].ToString() + ",";
                        CardNOList_D.Add(GetCardNOListByBox(d["boxno"].ToString(), dv), d["boxno"].ToString());
                    }
                }
                BoxNOList = "'" + BoxNOList.TrimEnd(',') + "'";
            }
        }
        /// <summary>
        /// 根据箱号获取盒号，并用“|”拼接
        /// </summary>
        /// <param name="box"></param>
        /// <param name="dvAll"></param>
        /// <returns></returns>
        private string GetCardNOListByBox(string box, DataView dvAll)
        {
            string cardNoStr = "";
            for (int i = 0; i < dvAll.Count; i++)
            {
                if (dvAll[i]["boxno"].ToString() == box)
                    cardNoStr += dvAll[i]["cardno"].ToString() + "|";
            }
            return cardNoStr.TrimEnd('|');
        }
        #endregion
    }
}